package cm.android.mytodoit.view;

import java.util.ArrayList;

import cm.android.mytodoit.R;
import cm.android.mytodoit.controller.Todo_SQLOpenHelper;
import cm.android.mytodoit.controller.listeners.TodiListViewOnItemClickListener;
import cm.android.mytodoit.model.TodoElement;

import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Window;
import android.widget.ArrayAdapter;


public class TodoListView extends ListActivity {

	private SQLiteDatabase database;
	private Todo_SQLOpenHelper sqlOpenHelper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.todolistview);

		this.sqlOpenHelper = new Todo_SQLOpenHelper(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		database = sqlOpenHelper.getReadableDatabase();
		
		ArrayList<TodoElement> todoElements = new ArrayList<TodoElement>();
		
		Cursor cursor = database.query(TodoElement.TABLE_NAME,
				null, // all columns 
				null,
				null,
				null,
				null,
				TodoElement.TC_PRIORITY);
		
		while (cursor.moveToNext()) {
			
			TodoElement element = new TodoElement();
			element.setId(cursor.getInt(cursor.getColumnIndex(TodoElement.TC_ID)));
			element.setTitle(cursor.getString(cursor.getColumnIndex(TodoElement.TC_TITLE)));
			element.setDescription(cursor.getString(cursor.getColumnIndex(TodoElement.TC_DESCRIPTION)));
			element.setPriority(cursor.getInt(cursor.getColumnIndex(TodoElement.TC_PRIORITY)));
			element.setInitialDate(cursor.getString(cursor.getColumnIndex(TodoElement.TC_INITIALDATE)));
			element.setExpirationDate(cursor.getString(cursor.getColumnIndex(TodoElement.TC_EXPIRATIONDATE)));
			todoElements.add(element);
			
		}
		
		ArrayAdapter<TodoElement> arrayAdapter = new ArrayAdapter<TodoElement>(this, android.R.layout.simple_list_item_1, todoElements);
		
		this.getListView().setAdapter(arrayAdapter);
		this.getListView().setOnItemClickListener(new TodiListViewOnItemClickListener(this));
	}

	@Override
	protected void onPause() {
		database.close();
		super.onPause();
	}

}
